package org.smarthings.things.automation.engine;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smarthings.things.automation.Action;
import org.smarthings.things.automation.Condition;
import org.smarthings.things.automation.Rule;
import org.smarthings.things.automation.scripting.engine.ScriptingContexBuilder;
import org.smarthings.things.automation.scripting.engine.ScriptingContext;
import org.smarthings.things.automation.scripting.engine.ScriptingEngineFacade;

import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EventBean;
import com.espertech.esper.client.StatementAwareUpdateListener;

public class CEPStatementListener implements StatementAwareUpdateListener {

	private final static Logger logger = LoggerFactory.getLogger(CEPStatementListener.class);

	private Rule rule;
	private ScriptingEngineFacade scriptingEngine;

	public CEPStatementListener(Rule rule, ScriptingEngineFacade scriptingEngine) {
		this.rule = rule;
		this.scriptingEngine = scriptingEngine;
	}

	public void update(EventBean[] newEvents, EventBean[] oldEvents, EPStatement statement,
			EPServiceProvider eventProcessingService) {
		System.out.println("Firing rule with UUID " + rule.getUUID());
		logger.info("Firing rule with UUID " + rule.getUUID());
		ScriptingContext context = ScriptingContexBuilder.create().rule(rule).events(newEvents)
				.build();
		try {
			Condition condition = rule.getCondition();
			Action action = rule.getAction();
			if (((Boolean) scriptingEngine.evaluate(condition.getLanguage(), //
					condition.getScript(), context)).booleanValue()) {
				scriptingEngine.evaluate(action.getLanguage(), action.getScript(), context);
			}
		} catch (Exception e) {
			logger.error("Error while firing rule with UUID " + rule.getUUID(), e);
			e.printStackTrace();
		}

	}
}
